package com.jt.www.hadoopcould.controller;


import com.jt.www.hadoopcould.model.HadoopFile;
import com.jt.www.hadoopcould.model.user;
import com.jt.www.hadoopcould.service.HadoopFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@SpringBootApplication
public class HadoopFileController {
    @Autowired
    HadoopFileService hadoopFileService;

    @Autowired
    HttpServletRequest request;



    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestParam("file")MultipartFile file){
        InputStream inputStream=null;
        try {

            String oldename=file.getOriginalFilename();
            String suffixName = oldename.substring(oldename.lastIndexOf("."));
            String newname= "37niuwei"+oldename;
            user user=(user)request.getSession().getAttribute("user");
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String filetime=sdf.format(date);
            System.out.println(oldename);
            System.out.println(suffixName);
            System.out.println(newname);

            HadoopFile hadoopFile = new HadoopFile();
            hadoopFile.setFileName(oldename);
            hadoopFile.setCreatTime(filetime);
            hadoopFile.setFileSize(file.getSize()+"");
            hadoopFile.setFileType(suffixName);
            hadoopFile.setUserid(user.getUserid());
            hadoopFile.setFileUrl("/opt/"+newname);

            File lsfile=new File("D://upload/"+newname);
            file.transferTo(lsfile);
            inputStream=new FileInputStream("D://upload/"+newname);
           hadoopFileService.addFile(hadoopFile,inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "success";
    }
}
